# coding:utf-8
from aliyunsdkcore import client
from aliyunsdkslb.request.v20140515 import RemoveBackendServersRequest, AddBackendServersRequest

import time
import json
import requests

class SLBmanage(object):
    def __init__(self):
        self.api_key_id = ""
        self.api_key_secret = ""
        self.region_id = ""

    def start_clt(self):
        clt = client.AcsClient(self.api_key_id, self.api_key_secret, self.region_id)
        return clt

    def removeBack(self, slbid, backlist, clt):
        return_data = {"status":False}
        try:
            request = RemoveBackendServersRequest.RemoveBackendServersRequest()
            request.set_accept_format('json')
            request.set_LoadBalancerId(slbid)
            request.set_BackendServers(backlist)
            response = clt.do_action_with_exception(request)
            return_data["status"] = True
        except BaseException as b:
            _log_err = "removeBack异常 --》 主机id：%s， 异常：%s" % (backlist, str(b))
            print(_log_err)
        finally:
            return return_data

    def addBack(self, slbid, backlist, request_url, clt):
        return_data = {"status": 4} #代表无法添加
        try:
            if self.slb_request(request_url):
                request = AddBackendServersRequest.AddBackendServersRequest()
                request.set_accept_format('json')
                request.set_LoadBalancerId(slbid)
                request.set_BackendServers(backlist)
                response = clt.do_action_with_exception(request)
                return_data["status"] = 0
            else:
                return_data["status"] = 5 #代表无法访问
        except BaseException as b:
            _log_err = "addBack异常 --》 主机id：%s， 异常：%s" % (backlist, str(b))
            print(_log_err)
        finally:
            return return_data

    def slb_request(self, request_url):
        cyc_status = True
        start_time = int(time.time())
        while cyc_status:
            end_data = int(time.time())
            elapsed = end_data - start_time
            if elapsed > 180:  # 超时2分钟
                cyc_status = False
                print("访问超时")
                return False
            try:
                r = requests.post(request_url)
                if r.status_code == 200:
                    cyc_status = False
                    print("访问成功")
                    return True
                else:
                    print("访问失败")
            except:
                pass 
             
    
    
